package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func UpdateAgentByTransactions(tx *gorm.DB, agent *models_main.Agent) error {
	err := tx.
		Save(agent).
		Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}

func InsertAgentByTransactions(tx *gorm.DB, agent *models_main.Agent) error {
	err := tx.
		Create(agent).
		Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}
func InsertAgent(agent *models_main.Agent) error {
	err := mysql.GetXTable(&models_main.Agent{}).
		Create(agent).
		Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}
func GetAgentByUid(uid uint) (*models_main.Agent, error) {
	agent := &models_main.Agent{}
	err := global.GetR().
		Model(&models_main.Agent{}).
		Where("uid", uid).
		Take(agent).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return agent, nil
}
